<template>
  <div class="formVant">
    <van-form ref="vanform" validate-first scroll-to-error error-message-align="right">
      <template v-for="item in formOptions">
        <!-- input 输入类型 -->
        <template v-if="item.type === 'input'">
          <van-field
            v-model.trim="localData[item.prop]"
            :key="item.prop"
            :name="item.label"
            :label="item.label"
            :placeholder="item.placeholder"
            :disabled="item.disabled"
            :required="item.required"
            :rules="[{ required: item.required, message: item.message || '该项为必填项' }]"
            autocomplete="false"
            maxlength="50"
            clearable
          >
          </van-field>
        </template>
        <template v-if="item.type === 'textarea'">
          <van-field
            v-model.trim="localData[item.prop]"
            :key="item.prop"
            :name="item.label"
            :label="item.label"
            :placeholder="item.placeholder"
            :disabled="item.disabled"
            :required="item.required"
            type="textarea"
            rows="3"
            :rules="[{ required: item.required, message: item.message || '该项为必填项' }]"
            autocomplete="false"
            maxlength="50"
            clearable
          >
          </van-field>
        </template>
        <!-- upload 上传类型 -->
        <template v-if="item.type === 'upload'">
          <van-field
            class="upload-wrap"
            :key="item.prop"
            :name="item.prop"
            :label="item.label"
            :rules="[
              {
                validator: (value) => !item.required || localData[item.prop]?.length > 0,
                message: item.message || `请上传${item.label}`
              }
            ]"
            :required="item.required"
          >
            <template #input>
              <UploadForImage
                v-model:fileList="localData[item.prop]"
                :key="item.prop"
                :uploadType="item.uploadType"
              />
            </template>
          </van-field>
        </template>
        <!-- mappicker地图选点类型 -->
        <template v-else-if="item.type === 'mappicker'">
          <van-field
            v-model.trim="localData[item.prop]"
            :key="item.prop"
            :name="item.prop"
            :label="item.label"
            :required="item.required"
            :rules="[{ required: item.required, message: item.message || '该项为必填项' }]"
          >
            <template #input>
              <div @click="mapSelect" class="mapSelect">{{ localData[item.prop] }}</div>
            </template>
          </van-field>
        </template>
      </template>
      <van-button round block type="primary" native-type="submit" @click="handlesubmit">
        提交认证
      </van-button>
    </van-form>
  </div>
</template>
<script lang="ts" setup>
import type { PropType } from 'vue'
import { useRouter } from 'vue-router'
import { useLocationStore } from '@/stores/locationStore'
const locationStore = useLocationStore()
interface FormOption {
  type: string // 输入框类型，如 'input'
  prop: string // 数据字段名
  label?: string // 标签文本
  placeholder?: string // 占位符
  disabled?: boolean // 是否禁用
  required?: boolean // 是否必填
  validator?: (value: any) => boolean // 验证函数
  message?: string // 错误提示信息
  uploadType?: string //区分上产的类型
}
const vanform = ref()
const router = useRouter()
const props = defineProps({
  formOptions: {
    type: Array as PropType<FormOption[]>,
    default: () => []
  },
  data: {
    type: Object as PropType<Record<string, any>>,
    default: () => ({})
  }
})
const localData = reactive(JSON.parse(JSON.stringify(toRaw(props.data))))
const emit = defineEmits(['update:data', 'submit'])
watch(
  () => props.data,
  (newVal) => {
    try {
      const newData = JSON.parse(JSON.stringify(toRaw(newVal)))
      Object.keys(newData).forEach((key) => {
        localData[key] = newData[key]
      })
    } catch (e) {
      console.error('数据克隆失败:', e)
    }
  },
  { deep: true }
)

watch(
  () => toRaw(localData),
  (newVal) => {
    try {
      emit('update:data', JSON.parse(JSON.stringify(toRaw(newVal))))
    } catch (e) {
      console.error('数据更新失败:', e)
    }
  },
  { deep: true }
)
watch(
  () => locationStore.selectedLocation,
  (newVal) => {
    console.log('newVal', newVal)
    if (newVal) {
      localData.address = newVal.address
    }
  }
)
const mapSelect = () => {
  router.push({
    name: 'mapPicker'
  })
}
const handlesubmit = async () => {
  try {
    await vanform.value?.validate()
    const formData = toRaw(localData)
    if (formData.front.length === 0) {
      return showToast('请上传正面照')
    }
    if (formData.back.length === 0) {
      return showToast('请上传正面照')
    }
    console.log('验证通过的表单数据:', formData)

    emit('submit', {
      ...formData,
      districtCode: locationStore?.selectedLocation?.districtCode,
      lat: locationStore?.selectedLocation?.lat,
      lng: locationStore?.selectedLocation?.lng
    })
  } catch (error) {
    console.error('表单验证失败:', error)
    // 验证失败时自动滚动到第一个错误字段（由vant自动处理）
  }
}
</script>
<style lang="scss" scoped>
.formVant {
  padding: 20px 12px;
  .van-field {
    width: 351px;
    border-radius: 23px 23px 23px 23px;
    border: 1px solid #dddddd;
    margin-bottom: 20px;
    &.upload-wrap {
      border: none;
    }
  }
  :deep(.van-field__control--custom) {
    justify-content: center;
  }
  .van-button--primary {
    background-color: #32bc05;
  }
  .mapSelect {
    width: 200px;
    min-height: 26px;
  }
}
</style>
